package com.wangp.mywrite.s_netty.chat_group.protocol;

import com.wangp.mywrite.s_netty.chat_group.config.Config;
import com.wangp.mywrite.s_netty.chat_group.message.LoginRequestMessage;
import com.wangp.mywrite.s_netty.chat_group.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author tooStronger
 * @date 2023/4/22
 */
public class TestSerializer {

    public static void main(String[] args) {
        MessageCodecSharable codec = new MessageCodecSharable();
        LoggingHandler loggingHandler = new LoggingHandler();
        EmbeddedChannel channel = new EmbeddedChannel(loggingHandler, codec, loggingHandler);

        LoginRequestMessage msg = new LoginRequestMessage("zhangsan", "123");
//        channel.writeOutbound(msg);
        ByteBuf byteBuf = messageToByteBuf(msg);
        channel.writeInbound(byteBuf);

    }


    public static ByteBuf messageToByteBuf(Message msg) {
        int algorithm = Config.getSerializerAlgorithm().ordinal();
        ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
        out.writeBytes(new byte[]{1, 2, 3, 4});
        out.writeByte(1);
        out.writeByte(algorithm);
        out.writeByte(msg.getMessageType());
        out.writeInt(msg.getSequenceId());
        out.writeByte(0xff);
        byte[] bytes = Serializer.Algorithm.values()[algorithm].serialize(msg);
        out.writeInt(bytes.length);
        out.writeBytes(bytes);
        return out;
    }
}
